
	//	set global object
	//	=================
		var __readable_by_evernote = {};

		
	//	first run
	//	=========
		
	window.addEventListener('load', function ()
	{
		//	check
		//	=====
			
			var 
				_prefs_service = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService),
				_prefs = _prefs_service.getBranch("extensions.readable-by-evernote.")
			;
			
			//	check -- maybe return
			if (_prefs.getCharPref('notFirstRun') == 'yes') { return; }
			
			//	set
			_prefs.setCharPref('notFirstRun', 'yes');
			
			
		//	actually run
		//	============
		
			//	add button
			__readable_by_evernote.installButtonForReadable("nav-bar", "readable_by_evernote__button");
			
			//	open info url
			gBrowser.selectedTab = gBrowser.addTab("http://www.evernote.com/clearly/"); 
	
	}, false);
	
	
	/** 
	 * https://developer.mozilla.org/en/Code_snippets/Toolbar#Adding_button_by_default
	 * + the old toolbar-button-init.js in the Firefox Evernote Cliper
	 * + some meddling
	 */  
	__readable_by_evernote.installButtonForReadable = function (_toolbarId, _buttonId)
	{
		//	already exists
		if (document.getElementById(_buttonId)) { return; }

		//	toolbar
		var _toolbar = document.getElementById(_toolbarId);  
		if (_toolbar); else { return; }
  
		//	insert
		var _set = _toolbar.getAttribute('currentset');
			_set = (_set > '' ? _set : _toolbar.getAttribute('defaultset'));
			_set += ',' + _buttonId;
			
		//	add
		_toolbar.insertItem(_buttonId, null, null, false);
		_toolbar.setAttribute('currentset', _set);
		_toolbar.currentset = _set;
		
		//	persist
		try { BrowserToolboxCustomizeDone(true); } catch (e) { }
		document.persist(_toolbarId, 'currentset');
	};



	//	bind fast
	//	=========
		
	//	hooks
	//	=====
		__readable_by_evernote.readable_by_evernote__menu__call = 			function () { __readable_by_evernote.__readable_by_evernote__launch(); };
		__readable_by_evernote.readable_by_evernote__context_menu__call = 	function () { __readable_by_evernote.__readable_by_evernote__launch(); };
		__readable_by_evernote.readable_by_evernote__button__call = 		function () { __readable_by_evernote.__readable_by_evernote__launch(); };

		
	//	jquery, keyboard
	//	================
		window.addEventListener('load', function ()
		{
			//	decode
			
	//	encode
	//	======
		function __encodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == '') { return 'none'; }
			
			//	encode
			return encodeURIComponent(_string)
				.replace(/!/g, '%21')
				.replace(/'/g, '%27')
				.replace(/\(/g, '%28')
				.replace(/\)/g, '%29')
				.replace(/\*/g, '%2A')
			;
		}

		
	//	decode
	//	======
		function __decodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == 'none') { return ''; }
			
			//	decode
			return decodeURIComponent(_string);
		}
	
	

				
			//	keyboard
			//	========
				var 
					_vars = __readable_by_evernote.__get_saved__vars(),
					__key_activation = __decodeURIComponentForReadable(_vars['keys_activation']),
					__key_clip = __decodeURIComponentForReadable(_vars['keys_clip'])
				;
				
				gBrowser.addEventListener('keydown', function(_event)
				{
					//	include key combo detection
						
	/*
		_event must be defined
		_key_combo and _key_code will be defined at end of code
	*/

	var _key_code = 'NONE';
	switch (true)
	{
		case (_event.keyCode && (_event.keyCode >= 65 && _event.keyCode <= 90)):
			_key_code = String.fromCharCode(_event.keyCode).toUpperCase();
			break;
			
		case (_event.keyCode == 27):	_key_code = 'Escape';		break;
		case (_event.keyCode == 37):	_key_code = 'Left Arrow';	break;
		case (_event.keyCode == 39):	_key_code = 'Right Arrow';	break;
		case (_event.keyCode == 38):	_key_code = 'Up Arrow';		break;
		case (_event.keyCode == 40):	_key_code = 'Down Arrow';	break;
	}

	//	get
	//	===
		var _modifierKeys = (_event.originalEvent ? _event.originalEvent : _event);
		//	jQuery screws up -- fucks up the metaKey property badly
		
		var _key_combo = ''
			+ (_modifierKeys.ctrlKey ? 'Control + ' : '')
			+ (_modifierKeys.shiftKey ? 'Shift + ' : '')
			+ (_modifierKeys.altKey ? 'Alt + ' : '')
			+ (_modifierKeys.metaKey ? 'Command + ' : '')
			+ _key_code
		;

	//	needs a modifier -- if not just Escape key
	//	================
		if ((_key_code != 'Escape') && (_key_code == _key_combo))
		{
			_key_code = 'NONE';
			_key_combo = 'NONE';
		}

					
					switch (true)
					{
						case ((__key_activation > '') && (_key_combo == __key_activation)):
						case ((__key_clip > '') && (_key_combo == __key_clip)):
							
							//	also clip?
							//	==========
								var __clip_on_launch = ((__key_clip > '') && (_key_combo == __key_clip));

							//	stop
							//	====
								_event.stopPropagation();
								_event.preventDefault();
								
							//	do
							//	==
								__readable_by_evernote.__readable_by_evernote__launch(__clip_on_launch);

							break;
					}
				}, true);
		}, false);

	
	//	launcher
	//	========
		__readable_by_evernote.__readable_by_evernote__launch = function (__clip_on_launch)
		{
			//	default
			if (__clip_on_launch); else { __clip_on_launch = false; }
			
			var 
				_d = gBrowser.contentDocument, 
				_b = _d.getElementsByTagName('body')[0], 
				_o = _d.getElementById('__readable_extension_definitions'), 
				_l = _d.createElement('script')
			;

			//	create, if not present
			//	======================
				if (_o); else
				{
					_o = _d.createElement('dl');
					_o.setAttribute('style', 'display: none;');
					_o.setAttribute('id', '__readable_extension_definitions');
					_b.appendChild(_o);
				}

			//	set options
			//	===========
				var
					_options = __readable_by_evernote.__get_saved__options(),
					_vars = __readable_by_evernote.__get_saved__vars(),
					_translations = __readable_by_evernote.__get_translations(),
					
					__definition_items_html = __readable_by_evernote.__get__stuffAsDefinitionItemsHTML
					({
						'option': _options,
						'var': _vars,
						'translation': _translations
					})
				;

				_o.innerHTML = __definition_items_html;

			//	launch in context
			//	=================
				_l.setAttribute('src', 'chrome://readable-by-evernote/content/js/__bookmarklet_to_inject'+(__clip_on_launch ? '__andClipOnLaunch' : '')+'.js');
				_l.className = 'bookmarklet_launch';
				_b.appendChild(_l);
			
			//	custom events
			//	=============
				__readable_by_evernote.__add_custom_events_handler();
		};


		
	//	include
	//	=======
		
		//	options
		
	//	get options
	//	===========
		__readable_by_evernote.__get_saved__options = function ()
		{
			
	//	encode
	//	======
		function __encodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == '') { return 'none'; }
			
			//	encode
			return encodeURIComponent(_string)
				.replace(/!/g, '%21')
				.replace(/'/g, '%27')
				.replace(/\(/g, '%28')
				.replace(/\)/g, '%29')
				.replace(/\*/g, '%2A')
			;
		}

		
	//	decode
	//	======
		function __decodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == 'none') { return ''; }
			
			//	decode
			return decodeURIComponent(_string);
		}
	
	

			
	//	__encodeURIComponentForReadable must be defined

	var __default_options = 
	{
		'text_font': 			__encodeURIComponentForReadable('"PT Serif"'),
		'text_font_header': 	__encodeURIComponentForReadable('"PT Serif"'),
		'text_font_monospace': 	__encodeURIComponentForReadable('Inconsolata'),
		'text_size': 			__encodeURIComponentForReadable('16px'),
		'text_line_height': 	__encodeURIComponentForReadable('1.5em'),
		'box_width': 			__encodeURIComponentForReadable('36em'),
		'color_background': 	__encodeURIComponentForReadable('#f3f2ee'),
		'color_text': 			__encodeURIComponentForReadable('#1f0909'),
		'color_links': 			__encodeURIComponentForReadable('#065588'),
		'text_align': 			__encodeURIComponentForReadable('normal'),
		'base': 				__encodeURIComponentForReadable('theme-1'),
		'footnote_links': 		__encodeURIComponentForReadable('on_print'),
		'large_graphics': 		__encodeURIComponentForReadable('do_nothing'),
		'custom_css': 			__encodeURIComponentForReadable(''
								+ '#text blockquote { border-color: #bababa; color: #656565; }'
								+ '#text thead { background-color: #dadada; }'
								+ '#text tr:nth-child(even) { background: #e8e7e7; }'
								)
	};


			var 
				_prefs_service = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService),
				_prefs = _prefs_service.getBranch("extensions.readable-by-evernote.")
			;

			var _return = {};
			for (var _x in __default_options) { _return[_x] = _prefs.getCharPref(_x); }
			
			return _return;
		};

		
	//	get vars	
	//	========
		__readable_by_evernote.__get_saved__vars = function ()
		{
			
	//	encode
	//	======
		function __encodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == '') { return 'none'; }
			
			//	encode
			return encodeURIComponent(_string)
				.replace(/!/g, '%21')
				.replace(/'/g, '%27')
				.replace(/\(/g, '%28')
				.replace(/\)/g, '%29')
				.replace(/\*/g, '%2A')
			;
		}

		
	//	decode
	//	======
		function __decodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == 'none') { return ''; }
			
			//	decode
			return decodeURIComponent(_string);
		}
	
	

			
	//	__encodeURIComponentForReadable must be defined

	var __default_vars = 
	{
		'theme': 				__encodeURIComponentForReadable('theme-1'),
		
		'keys_activation': 		__encodeURIComponentForReadable('Control + Alt + Right Arrow'),
		'keys_clip': 			__encodeURIComponentForReadable('Control + Alt + Up Arrow'),
		'clip_tag': 			__encodeURIComponentForReadable(''),
		
		'custom_theme_options':	__encodeURIComponentForReadable('')
	};

		
			var 
				_prefs_service = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService),
				_prefs = _prefs_service.getBranch("extensions.readable-by-evernote.")
			;

			var _return = {};
			for (var _x in __default_vars) { _return[_x] = _prefs.getCharPref(_x); }
			
			return _return;
		};
		

	//	save
	//	====
		__readable_by_evernote.__save_someStuff = function (_to_save)
		{
			var 
				_prefs_service = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService),
				_prefs = _prefs_service.getBranch("extensions.readable-by-evernote.")
			;
		
			for (var _x in _to_save)
				{ _prefs.setCharPref(_x, _to_save[_x]); }
		};
		
		
	//	get definitionList
	//	==================
		__readable_by_evernote.__get__stuffAsDefinitionItemsHTML = function (_stuffToTransform)
		{
			/*
				stuffToTransform = {
					'prefix-id': {
						'key': 'value'
					}
				};
			*/
			
            //  __escapeForHTML
            
    //  escapeForHTML
    //  =============
        function __escapeForHTML(_string)
        {
            var _replace = {
                "&": "amp", 
                '"': "quot", 
                "<": "lt", 
                ">": "gt"
            };
            
            return _string.replace(
                /[&"<>]/g,
                function (_match) { return ("&" + _replace[_match] + ";"); }
            );
        }

            
            //  create html
			var _html = '';
			for (var _prefix in _stuffToTransform)
			{
				for (var _x in _stuffToTransform[_prefix])
				{
					_html += ''
						+ '<dd id="__readable_' + __escapeForHTML(_prefix) + '__' + __escapeForHTML(_x) + '">'
						+ 	__escapeForHTML(_stuffToTransform[_prefix][_x])
						+ '</dd>'
					;
				}
			}
			
			return _html;
		};

		
	//	set defaults -- are set in defaults/preferences/prefs.js to '--def--'
	//	============
		(function ()
		{
			
	//	encode
	//	======
		function __encodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == '') { return 'none'; }
			
			//	encode
			return encodeURIComponent(_string)
				.replace(/!/g, '%21')
				.replace(/'/g, '%27')
				.replace(/\(/g, '%28')
				.replace(/\)/g, '%29')
				.replace(/\*/g, '%2A')
			;
		}

		
	//	decode
	//	======
		function __decodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == 'none') { return ''; }
			
			//	decode
			return decodeURIComponent(_string);
		}
	
	

			
	//	__encodeURIComponentForReadable must be defined

	var __default_options = 
	{
		'text_font': 			__encodeURIComponentForReadable('"PT Serif"'),
		'text_font_header': 	__encodeURIComponentForReadable('"PT Serif"'),
		'text_font_monospace': 	__encodeURIComponentForReadable('Inconsolata'),
		'text_size': 			__encodeURIComponentForReadable('16px'),
		'text_line_height': 	__encodeURIComponentForReadable('1.5em'),
		'box_width': 			__encodeURIComponentForReadable('36em'),
		'color_background': 	__encodeURIComponentForReadable('#f3f2ee'),
		'color_text': 			__encodeURIComponentForReadable('#1f0909'),
		'color_links': 			__encodeURIComponentForReadable('#065588'),
		'text_align': 			__encodeURIComponentForReadable('normal'),
		'base': 				__encodeURIComponentForReadable('theme-1'),
		'footnote_links': 		__encodeURIComponentForReadable('on_print'),
		'large_graphics': 		__encodeURIComponentForReadable('do_nothing'),
		'custom_css': 			__encodeURIComponentForReadable(''
								+ '#text blockquote { border-color: #bababa; color: #656565; }'
								+ '#text thead { background-color: #dadada; }'
								+ '#text tr:nth-child(even) { background: #e8e7e7; }'
								)
	};

			
	//	__encodeURIComponentForReadable must be defined

	var __default_vars = 
	{
		'theme': 				__encodeURIComponentForReadable('theme-1'),
		
		'keys_activation': 		__encodeURIComponentForReadable('Control + Alt + Right Arrow'),
		'keys_clip': 			__encodeURIComponentForReadable('Control + Alt + Up Arrow'),
		'clip_tag': 			__encodeURIComponentForReadable(''),
		
		'custom_theme_options':	__encodeURIComponentForReadable('')
	};

		
			var 
				_prefs_service = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService),
				_prefs = _prefs_service.getBranch("extensions.readable-by-evernote.")
			;
		
			//	mac or pc
			//	=========
				var osString = Components.classes["@mozilla.org/xre/app-info;1"].getService(Components.interfaces.nsIXULRuntime).OS;
				if (osString.toLowerCase() == 'darwin')
				{
					__default_vars['keys_activation'] = __encodeURIComponentForReadable('Control + Command + Right Arrow');
					__default_vars['keys_clip'] = 		__encodeURIComponentForReadable('Control + Command + Up Arrow');
				}
		
			//	options
			//	=======
				for (var _x in __default_options)
				{
					var 
						_valueNow = _prefs.getCharPref(_x),
						_valueDefault = __default_options[_x]
					;
					
					switch (true)
					{
						case (!(_valueNow > '')):
						case (_valueNow == '--def--'):
							_prefs.setCharPref(_x, _valueDefault);
							break;
					}
				}
				
			//	vars
			//	====
				for (var _x in __default_vars)
				{
					var 
						_valueNow = _prefs.getCharPref(_x),
						_valueDefault = __default_vars[_x]
					;
					
					switch (true)
					{
						case (!(_valueNow > '')):
						case (_valueNow == '--def--'):
							_prefs.setCharPref(_x, _valueDefault);
							break;
					}
				}
		})();
		

		//	evernote remote
		
	//	included code
	//	json-rpc must exist in context

	
	//	namespace
	//	=========
		__readable_by_evernote.__evernote_remote =
		{
			'domain': 			'https://www.evernote.com/',
			
			'api__key': 		'en-clearly',
			'api__secret': 		'6798bce902c29b73',
			
			'rpc__userStore': 	false,
			'rpc__noteStore': 	false,
			
			'user__authToken': 	false,
			'user__shardId': 	false,
			'user__privilege': 	false,
			
			'is__connected': 	false,
			'is__loggedIn': 	false
		};

	
	//	connect
	//	=======
		__readable_by_evernote.__evernote_remote.connect = function (_onSuccess, _onFailure)
		{
			try
            {
                __readable_by_evernote.__evernote_remote.rpc__userStore = new __readable_by_evernote.JSONRpcClient
                (
                    function ()
                    {
                        //	error
                        if (__readable_by_evernote.__evernote_remote.rpc__userStore.UserStore); else
                            { _onFailure('connection / invalid'); return; }
                    
                        //	set conected
                        __readable_by_evernote.__evernote_remote.is__connected = true;
                        
                        //  run
                        _onSuccess();
                    }, 
                    __readable_by_evernote.__evernote_remote.domain + 'json'
                );
            }
			catch (_error) { _onFailure('connection / invalid'); return; }
		};

	
	//	logout
	//	======
		__readable_by_evernote.__evernote_remote.logout = function ()
		{
			__readable_by_evernote.__evernote_remote['rpc__userStore'] = 	false;
			__readable_by_evernote.__evernote_remote['rpc__noteStore'] = 	false;

			__readable_by_evernote.__evernote_remote['user__authToken'] = 	false;
			__readable_by_evernote.__evernote_remote['user__shardId'] = 	false;
			__readable_by_evernote.__evernote_remote['user__privilege'] = 	false;

			__readable_by_evernote.__evernote_remote['is__connected'] = 	false;
			__readable_by_evernote.__evernote_remote['is__loggedIn'] = 	false;
		};
		
		
	//	login
	//	=====
		__readable_by_evernote.__evernote_remote.login = function (_user, _pass, _onSuccess, _onFailure)
		{
            //  login function
            //  ===============
                var _loginFunction = function ()
                {
                    //	login
                    //	=====
                        try
                        {
                            var _loginResult = __readable_by_evernote.__evernote_remote.rpc__userStore.UserStore.authenticate
                            (
                                _user, 							// username
                                _pass, 							// password
                                __readable_by_evernote.__evernote_remote.api__key,		// consumer key
                                __readable_by_evernote.__evernote_remote.api__secret	// consumer secret
                            );
                        }
                        catch (_error)
                        {
                            //	unknown error
                            //	=============
                                switch (true)
                                {
                                    case (!(_error.trace)):
                                    case (!(_error.trace.indexOf)):
                                    case (!(_error.trace.indexOf(')') > -1)):
                                        _onFailure('login / exception / no trace');
                                        return;
                                }
                            
                            //	figure out error
                            //	================
                                var _trace = _error.trace.substr(0, _error.trace.indexOf(')')+1);
                                switch (_trace)
                                {
                                    case 'EDAMUserException(errorCode:INVALID_AUTH, parameter:username)':
                                        _onFailure('username');
                                        return;

                                    case 'EDAMUserException(errorCode:INVALID_AUTH, parameter:password)':
                                        _onFailure('password');
                                        return;
                                }

                            //	could not figure out error
                            //	==========================
                                _onFailure('login / exception / unknown');
                                return;
                        }
                        
                        
                    //	check
                    //	=====
                        switch (true)
                        {
                            case (!(_loginResult.authenticationToken)):
                            case (!(_loginResult.user)):
                            case (!(_loginResult.user.shardId)):
                                _onFailure('login / invalid result');
                                return;
                        }
                        
                        
                    //	set userInfo
                    //	============
                        __readable_by_evernote.__evernote_remote.user__authToken = 		_loginResult.authenticationToken;
                        __readable_by_evernote.__evernote_remote.user__shardId = 		_loginResult.user.shardId;
                        __readable_by_evernote.__evernote_remote.user__privilege = 		_loginResult.user.privilege.value;
                    
                        __readable_by_evernote.__evernote_remote.is__loggedIn = true;
                        
                    
                    //	note store
                    //	==========
                    
                        //	make connection
                        try
                        {
                            __readable_by_evernote.__evernote_remote.rpc__noteStore = new __readable_by_evernote.JSONRpcClient
                            (
                                function ()
                                {
                                    //	error
                                    if (__readable_by_evernote.__evernote_remote.rpc__noteStore.NoteStore); else
                                        { _onFailure('login / note store / invalid'); return; }

                                    //  run
                                    _onSuccess();
                                },
                                __readable_by_evernote.__evernote_remote.domain + 'shard/' + __readable_by_evernote.__evernote_remote.user__shardId + '/json'
                            );
                        }
                        catch (_error) { _onFailure('login / note store / invalid'); return; }
                };

			//	allready connected, connect, or error
			//	=====================================
				if (__readable_by_evernote.__evernote_remote.is__connected)
                {
                    //  do
                    _loginFunction();
                }
                else
				{
					//	connect
					__readable_by_evernote.__evernote_remote.connect
                    (
                        function () { _loginFunction(); },
                        function () { _onFailure('connection / invalid'); }
                    );
				}
        };
	
	
	//	clip
	//	====
		__readable_by_evernote.__evernote_remote.clip = function (_url, _title, _body, _tag, _onSuccess, _onFailure)
		{
			//	preliminary check
			//	=================
				switch (true)
				{
					case (!(__readable_by_evernote.__evernote_remote.rpc__noteStore.NoteStore)):
					case (!(__readable_by_evernote.__evernote_remote.is__connected)):
					case (!(__readable_by_evernote.__evernote_remote.is__loggedIn)):
						_onFailure('login');
						return;
				}

				
			//	create tags array
			//	=================
				var
					_tags_we_should_set = _tag.split(','),
					_tags_we_will_set = []
				;

				for (var i=0, _i=_tags_we_should_set.length; i<_i;i++)
				{
					var _t = _tags_we_should_set[i].replace(/^ /, '').replace(/ $/, '')
					if (_t > ''); else { continue; }
					
					_tags_we_will_set.push(_t);
				}
				
				
			//	try and clip
			//	============
				try
				{
					var _clipResult = __readable_by_evernote.__evernote_remote.rpc__noteStore.NoteStoreExtra.clipNote
					(
						__readable_by_evernote.__evernote_remote.user__authToken, 	// authentification token
						{
							'tagNameList': _tags_we_will_set,
							'createTags': true,
							'source': 'Clearly'
						},															// filing information
						_title, 													// title
						_url, 														// url
						_body														// html
					);
				}
				catch (_error)
				{
					//	unknown error
					//	=============
						switch (true)
						{
							case (!(_error.trace)):
							case (!(_error.trace.indexOf)):
							case (!(_error.trace.indexOf(')') > -1)):
								_onFailure('clip / exception / no trace');
								return;
						}
					
					//	figure out error
					//	================
						var _trace = _error.trace.substr(0, _error.trace.indexOf(')')+1);
						switch (_trace)
						{
							case 'EDAMUserException(errorCode:BAD_DATA_FORMAT, parameter:authenticationToken)':
							case 'EDAMSystemException(errorCode:INVALID_AUTH, message:authenticationToken)':
							case 'EDAMUserException(errorCode:AUTH_EXPIRED, parameter:authenticationToken)':
								_onFailure('login');
								return;
						}

					//	could not figure out error
					//	==========================
						_onFailure('clip / exception / unknown');
						return;
				}

				
			//	check
			//	=====
				switch (true)
				{
					case (!(_clipResult > '')):
					case (!(_clipResult.split('-').length == 5)):
						_onFailure('clip / invalid result');
						return;
				}

				
			//	success
			//	=======
				_onSuccess();
		};

		/*
 * Evernote.XORCrypt
 * Evernote
 *
 * Created by Pavel Skaldin on 3/7/10
 * Copyright 2010 Evernote Corp. All rights reserved
 */
/**
 * Naive implementation of XOR encryption with padding. It is not meant to be a
 * strong encryption of any kind, just an obfuscation. The algorithm uses a seed
 * string for XORing. The string to be encrypted is first XOR'd with a random
 * number to avoid recognizable patterns; the result is then padded and then
 * XOR'd with the seed string.
 * 
 * Make sure that XORCrypt.LENGTH is larger than the strings you're trying to
 * encrypt.
 * 
 * <pre>
 * Usage: 
 * var enc = Evernote.XORCrypt.encrypt(secret, seed); 
 * var dec = Evernote.XORCrypt.decrypt(enc, seed);
 * </pre>
 */
__readable_by_evernote.__evernote_xor = {
  DELIMIT : ":",
  LENGTH : 128,
  /**
   * Pads string to make it XORCrypt.LENGTH characters in length. Padding is
   * done by prepending the string with random chars from a range of printable
   * ascii chars.
   */
  _padString : function(str) {
    var counter = 0;
    if (str.length < 128) {
      for ( var i = str.length; i <= 128; i++) {
        str = String.fromCharCode(this._randomForChar()) + str;
        counter++;
      }
    }
    return counter + this.DELIMIT + str;
  },
  /**
   * Returns random number that would correspond to a printable ascii char.
   */
  _randomForChar : function() {
    var r = 0;
    var c = 0;
    while (r < 33 || r > 126) {
      // just a waiting... this shouldn't happen frequently
      r = parseInt(Math.random() * 150);
      c++;
    }
    return r;
  },
  /**
   * Returns random non-zero integer.
   */
  _randomNonZero : function() {
    var r = 0;
    while ((r = parseInt(Math.random() * 100)) == 0) {
      // just a waiting... this shouldn't happen frequently
    }
    return r;
  },
  /**
   * Shifts string by XOR'ing it with a number larger than 100 so as to avoid
   * non-printable characters. The resulting string will be prepended with the
   * number used to XOR followed by DELIMITER.
   */
  _shiftString : function(str) {
    var delta = this._randomNonZero() + 100;
    var shifted = [];
    for ( var i = 0; i < str.length; i++) {
      shifted.push(String.fromCharCode(str.charCodeAt(i) + delta));
    }
    return delta + this.DELIMIT + shifted.join("");
  },
  /**
   * Unshifts and returns a shifted string. The argument should be in a format
   * produced by _shitString(), i.e. begin with the shift coefficient followed
   * by DELIMITER, followed by the shifted string.
   */
  _unshiftString : function(str) {
    var delta = parseInt(str.substring(0, str.indexOf(this.DELIMIT)));
    var unshifted = [];
    if (!isNaN(delta)) {
      for ( var i = ((delta + "").length + this.DELIMIT.length); i < str.length; i++) {
        unshifted.push(String.fromCharCode(str.charCodeAt(i) - delta));
      }
    }
    return unshifted.join("");
  },
  /**
   * Encrypts string with a seed string and returns encrypted string padded to
   * be XORCrypt.LENGTH characters long.
   */
  encrypt : function(str, seed) {
    str += "";
    seed += "";
    var newStr = this._padString(this._shiftString(str));
    var enc = [];
    for ( var i = 0; i < newStr.length; i++) {
      var e = newStr.charCodeAt(i);
      for ( var j = 0; j < seed.length; j++) {
        e = seed.charCodeAt(j) ^ e;
      }
      enc.push(String.fromCharCode(e + 100));
    }
    return enc.join("");
  },
  /**
   * Decrypts string using seed string. The seed string has to be the same
   * string that was used in encrypt()ing.
   */
  decrypt : function(str, seed) {
    str += "";
    seed += "";
    var dec = [];
    for ( var i = 0; i < str.length; i++) {
      var e = str.charCodeAt(i) - 100;
      for ( var j = seed.length - 1; j >= 0; j--) {
        e = seed.charCodeAt(j) ^ e;
      }
      dec.push(String.fromCharCode(e));
    }
    var decStr = dec.join("");
    var pad = parseInt(decStr.substring(0, decStr.indexOf(this.DELIMIT)));
    if (!isNaN(pad)) {
      return this._unshiftString(decStr.substring(("" + pad).length
          + this.DELIMIT.length + pad));
    }
    return "";
  }
};


		//	stored credentials
		
	//	get/set stored evernote credentials
	//	requires __evernote_xor present in context
	//	==========================================

	//	get
	//	===
		__readable_by_evernote.__get_stored_evernote_credentials = function ()
		{
			var
				_prefs_service = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService),
				_prefs = _prefs_service.getBranch("extensions.readable-by-evernote.")
			;
		
			var 
				_username = _prefs.getCharPref('storedEvernoteUsername'),
				_password = ''
				
				//_unicodeEncodedPassword = _prefs.getComplexValue("storedEvernotePassword", Components.interfaces.nsISupportsString)
				//_password = (_unicodeEncodedPassword.data > '' ? _unicodeEncodedPassword.data : '')
			;
				
			var 
				_login_service = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager),
				_logins = _login_service.findLogins({}, 'chrome://readable-by-evernote', '', 'Evernote Login')
			;

			for (var i=0, _i=_logins.length; i<_i; i++)
			{
				if (_logins[i].username == _username)
					{ _password = _logins[i].password; break; }
			}
				
			switch (true)
			{
				case (!(_username > '')):
				case (!(_password > '')):
					return false;
			}
		
			var _r = {};
				_r.username = _username;
				_r.password = _password;
				//_r.password = __readable_by_evernote.__evernote_xor.decrypt(_password, _r.username);
			return _r;
		};

		
	//	set
	//	===
		__readable_by_evernote.__set_stored_evernote_credentials = function (_o)
		{
			var 
				_prefs_service = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService),
				_prefs = _prefs_service.getBranch("extensions.readable-by-evernote.")
			;
		
			switch (true)
			{
				case (!(_o['username'] > '')):
				case (!(_o['password'] > '')):
					return false;
			}
			
			var 
				_login_service = Components.classes["@mozilla.org/login-manager;1"].getService(Components.interfaces.nsILoginManager),
				_login_info__class = new Components.Constructor("@mozilla.org/login-manager/loginInfo;1", Components.interfaces.nsILoginInfo, "init") 
				_login_info = new _login_info__class('chrome://readable-by-evernote', null, 'Evernote Login', _o.username, _o.password, '', '')
			;
			
			_prefs.setCharPref('storedEvernoteUsername', _o.username);
			try { _login_service.addLogin(_login_info); } catch (e) { }
			
			//	var _unicodeEncodedPassword = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
			//		_unicodeEncodedPassword.data = __readable_by_evernote.__evernote_xor.encrypt(_o['password'], _o['username']);
			//		_prefs.setComplexValue('storedEvernotePassword', Components.interfaces.nsISupportsString, _unicodeEncodedPassword);
			
			return true;
		};
		
		
	//	logout on next action
	//	=====================
	
		__readable_by_evernote.__get_stored_evernote_logoutOnNextAction = function ()
		{
			var
				_prefs_service = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService),
				_prefs = _prefs_service.getBranch("extensions.readable-by-evernote.")
			;
		
			if (_prefs.getCharPref('storedEvernoteLogoutOnNextAction') > ''); else { return false; }
			if (_prefs.getCharPref('storedEvernoteLogoutOnNextAction') == 'yes'); else { return false; }
			
			//	reset
			_prefs.setCharPref('storedEvernoteLogoutOnNextAction', '');
			
			//	return true
			return true;
		};
	
		__readable_by_evernote.__set_stored_evernote_logoutOnNextAction = function ()
		{
			var
				_prefs_service = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefService),
				_prefs = _prefs_service.getBranch("extensions.readable-by-evernote.")
			;

			//	set
			_prefs.setCharPref('storedEvernoteLogoutOnNextAction', 'yes');
		};

	
		//	select theme and size
		
	//	select theme
	//	============
		__readable_by_evernote.__save__select_theme = function (_theme_id)
		{
			//	the themes
			
	//	encode
	//	======
		function __encodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == '') { return 'none'; }
			
			//	encode
			return encodeURIComponent(_string)
				.replace(/!/g, '%21')
				.replace(/'/g, '%27')
				.replace(/\(/g, '%28')
				.replace(/\)/g, '%29')
				.replace(/\*/g, '%2A')
			;
		}

		
	//	decode
	//	======
		function __decodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == 'none') { return ''; }
			
			//	decode
			return decodeURIComponent(_string);
		}
	
	

			
	//	__encodeURIComponentForReadable must be defined

	var __the_themes = 
	{
		'theme-1':
		{
			'text_font': 			__encodeURIComponentForReadable('"PT Serif"'),
			'text_font_header': 	__encodeURIComponentForReadable('"PT Serif"'),
			'text_font_monospace': 	__encodeURIComponentForReadable('Inconsolata'),
			'text_size': 			__encodeURIComponentForReadable('16px'),
			'text_line_height': 	__encodeURIComponentForReadable('1.5em'),
			'box_width': 			__encodeURIComponentForReadable('36em'),
			'color_background': 	__encodeURIComponentForReadable('#f3f2ee'),
			'color_text': 			__encodeURIComponentForReadable('#1f0909'),
			'color_links': 			__encodeURIComponentForReadable('#065588'),
			'text_align': 			__encodeURIComponentForReadable('normal'),
			'base': 				__encodeURIComponentForReadable('theme-1'),
			'footnote_links': 		__encodeURIComponentForReadable('on_print'),
			'large_graphics': 		__encodeURIComponentForReadable('do_nothing'),
			'custom_css': 			__encodeURIComponentForReadable(''
									+ '#text blockquote { border-color: #bababa; color: #656565; }'
									+ '#text thead { background-color: #dadada; }'
									+ '#text tr:nth-child(even) { background: #e8e7e7; }'
									+ '#text hr { border-color: #c5c5c5; }'
									)
		},
		
		'theme-2':
		{
			'text_font': 			__encodeURIComponentForReadable('Helvetica, Arial'),
			'text_font_header': 	__encodeURIComponentForReadable('Helvetica, Arial'),
			'text_font_monospace': 	__encodeURIComponentForReadable('"Droid Sans Mono"'),
			'text_size': 			__encodeURIComponentForReadable('14px'),
			'text_line_height': 	__encodeURIComponentForReadable('1.5em'),
			'box_width': 			__encodeURIComponentForReadable('42em'),
			'color_background': 	__encodeURIComponentForReadable('#fff'),
			'color_text': 			__encodeURIComponentForReadable('#333'),
			'color_links': 			__encodeURIComponentForReadable('#090'),
			'text_align': 			__encodeURIComponentForReadable('normal'),
			'base': 				__encodeURIComponentForReadable('theme-2'),
			'footnote_links': 		__encodeURIComponentForReadable('on_print'),
			'large_graphics': 		__encodeURIComponentForReadable('do_nothing'),
			'custom_css': 			__encodeURIComponentForReadable(''
									+ '#text h1 { color: #000; }'
									+ '#text h2, #text h3, #text h4, #text h5, #text h6 { color: #444; }'
									+ '#text blockquote { border-color: #d1d1d1; }'
									+ '#text thead { background-color: #444; color: #fff; }'
									+ '#text tr:nth-child(even) { background: #d1d1d1; }'
									+ '#text hr { border-color: #000; }'
									)
		},
		
		'theme-3':
		{
			'text_font': 			__encodeURIComponentForReadable('"PT Serif"'),
			'text_font_header': 	__encodeURIComponentForReadable('"PT Serif"'),
			'text_font_monospace': 	__encodeURIComponentForReadable('Inconsolata'),
			'text_size': 			__encodeURIComponentForReadable('16px'),
			'text_line_height': 	__encodeURIComponentForReadable('1.5em'),
			'box_width': 			__encodeURIComponentForReadable('36em'),
			'color_background': 	__encodeURIComponentForReadable('#2d2d2d'),
			'color_text': 			__encodeURIComponentForReadable('#e3e3e3'),
			'color_links': 			__encodeURIComponentForReadable('#e3e3e3'),
			'text_align': 			__encodeURIComponentForReadable('normal'),
			'base': 				__encodeURIComponentForReadable('theme-3'),
			'footnote_links': 		__encodeURIComponentForReadable('on_print'),
			'large_graphics': 		__encodeURIComponentForReadable('do_nothing'),
			'custom_css': 			__encodeURIComponentForReadable(''
									+ '#text a:link { -webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease; -o-transition: all 0.3s ease; }'
									+ '#text a:hover, #text a:active {	color: #44bde8; }'
									+ '#text blockquote { color: #c1bfbf; border-color: #c1bfbf; }'
									+ '#text thead { background-color: #4f4f4f; }'
									+ '#text tr:nth-child(even) { background: #404040; }'
									+ '#text hr { border-color: #c5c5c5; }'
									)
		}
	};
			
			var _to_save = __the_themes[_theme_id];
				_to_save['theme'] = _theme_id;
				
			//	save
			__readable_by_evernote.__save_someStuff(_to_save);
		}

		__readable_by_evernote.__save__select_theme__custom = function ()
		{
			//	the themes
			
	//	encode
	//	======
		function __encodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == '') { return 'none'; }
			
			//	encode
			return encodeURIComponent(_string)
				.replace(/!/g, '%21')
				.replace(/'/g, '%27')
				.replace(/\(/g, '%28')
				.replace(/\)/g, '%29')
				.replace(/\*/g, '%2A')
			;
		}

		
	//	decode
	//	======
		function __decodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == 'none') { return ''; }
			
			//	decode
			return decodeURIComponent(_string);
		}
	
	


			//	to save
			var _to_save = {};
				_to_save['theme'] = 'custom';
				
			//	get custom
			var _vars = __readable_by_evernote.__get_saved__vars();
			__decodeURIComponentForReadable(_vars['custom_theme_options']).replace
			(
				/\[\[=(.*?)\]\[=(.*?)\]\]/gi,
				function (_match, _name, _value) { _to_save[_name] = _value; }
			);
				
			//	save
			__readable_by_evernote.__save_someStuff(_to_save);
		}
		
	
	//	select size
	//	===========
		__readable_by_evernote.__save__select_size = function (_size)
		{
			//	the sizes
			
	//	encode
	//	======
		function __encodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == '') { return 'none'; }
			
			//	encode
			return encodeURIComponent(_string)
				.replace(/!/g, '%21')
				.replace(/'/g, '%27')
				.replace(/\(/g, '%28')
				.replace(/\)/g, '%29')
				.replace(/\*/g, '%2A')
			;
		}

		
	//	decode
	//	======
		function __decodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == 'none') { return ''; }
			
			//	decode
			return decodeURIComponent(_string);
		}
	
	

			
	var __the_sizes = 
	{
		'small':
		{
			'theme-1': '12px',
			'theme-2': '12px',
			'theme-3': '12px',
			'custom':  '12px'
		},
	
		'medium':
		{
			'theme-1': '16px',
			'theme-2': '16px',
			'theme-3': '16px',
			'custom':  '16px'
		},
		
		'large':
		{
			'theme-1': '20px',
			'theme-2': '20px',
			'theme-3': '20px',
			'custom':  '20px'
		}
	};

		
			//	current vars
			var _current_vars = __readable_by_evernote.__get_saved__vars();
			
			//	save
			__readable_by_evernote.__save_someStuff(
				{ 'text_size': __the_sizes[_size][_current_vars['theme']] }
			);
		}


		//	translations
		
	__readable_by_evernote.__get_translations = function ()
	{
		//	include
		
	//	encode
	//	======
		function __encodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == '') { return 'none'; }
			
			//	encode
			return encodeURIComponent(_string)
				.replace(/!/g, '%21')
				.replace(/'/g, '%27')
				.replace(/\(/g, '%28')
				.replace(/\)/g, '%29')
				.replace(/\*/g, '%2A')
			;
		}

		
	//	decode
	//	======
		function __decodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == 'none') { return ''; }
			
			//	decode
			return decodeURIComponent(_string);
		}
	
	


		//	translations include
		
	function __get_translations_inside()
	{
		var 
			_return = {},
			_list =
			[
				'menu__close__tooltip',
				'menu__clip_to_evernote__tooltip',
				'menu__print__tooltip',
				'menu__settings__tooltip',
				'fitts__tooltip',
				
				'rtl__main__label',
				'rtl__ltr__label',
				'rtl__rtl__label',
				
				'blank_error__heading',
				'blank_error__body',
				
				'evernote_clipping',
				'evernote_clipping_failed',
				
				'evernote_login__heading',
				'evernote_login__spinner',
				'evernote_login__create_account',
				'evernote_login__button_do__label',
				'evernote_login__button_cancel__label',
				
				'evernote_login__username__label',
				'evernote_login__password__label',
				'evernote_login__rememberMe__label',
				
				'evernote_login__username__error__required',
				'evernote_login__username__error__length',
				'evernote_login__username__error__format',
				'evernote_login__username__error__invalid',
				
				'evernote_login__password__error__required',
				'evernote_login__password__error__length',
				'evernote_login__password__error__format',
				'evernote_login__password__error__invalid',
				
				'evernote_login__general__error',
				
				'settings__theme__1',
				'settings__theme__2',
				'settings__theme__3',
				'settings__theme__custom',
				
				'settings__fontSize__small',
				'settings__fontSize__medium',
				'settings__fontSize__large'
			]
		;
		
		for (var i=0,_i=_list.length; i<_i; i++) {
			_return[_list[i]] = __get_translations_inside__getForKey(_list[i]);
		}
		
		return _return;
	}


		//	translation function
		function __get_translations_inside__getForKey(_key)
		{
			//	will fail on missing string
			try {
				var _t = document.getElementById('readable_by_evernote__string_bundle__inside').getString('inside__'+_key);
				return (_t > '' ? _t : '');
			}
			catch (e) { }
			
			return '';
		}

		return __get_translations_inside();
	}


		
	//	events
	//	======
		
	__readable_by_evernote.__add_custom_events_handler = function ()
	{
		//	include
		
	//	encode
	//	======
		function __encodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == '') { return 'none'; }
			
			//	encode
			return encodeURIComponent(_string)
				.replace(/!/g, '%21')
				.replace(/'/g, '%27')
				.replace(/\(/g, '%28')
				.replace(/\)/g, '%29')
				.replace(/\*/g, '%2A')
			;
		}

		
	//	decode
	//	======
		function __decodeURIComponentForReadable(_string)
		{
			//	none
			if (_string == 'none') { return ''; }
			
			//	decode
			return decodeURIComponent(_string);
		}
	
	

					
		//	document
		var _d = gBrowser.contentDocument;
	
		//	just once
		if (_d.__readable_event_monitor_attached) { return; }
		_d.__readable_event_monitor_attached = true;
	
		//	include events
			
	/*
		first three variables will be defined
	*/

	var 
		__custom_events__names_to_keys = {},
		__custom_events__keys_to_names = {},
		__custom_events__names_to_objects = {},
		
		__custom_events =
		[
			['to-extension--open-settings', 				'click-110-120-130-140-1-1-1'],
			['to-extension--open-settings-theme', 			'click-111-121-131-141-1-1-1'],
			
			['to-extension--evernote-clip', 				'click-210-220-230-240-1-1-1'],
			['to-extension--evernote-login', 				'click-310-320-330-340-1-1-1'],

			['to-extension--select-theme-1', 				'click-511-521-531-541-1-1-1'],
			['to-extension--select-theme-2', 				'click-512-522-532-542-1-1-1'],
			['to-extension--select-theme-3', 				'click-513-523-533-543-1-1-1'],
			['to-extension--select-theme-custom', 			'click-514-524-534-544-1-1-1'],

			['to-extension--select-size-small', 			'click-611-621-631-641-1-1-1'],
			['to-extension--select-size-medium', 			'click-612-622-632-642-1-1-1'],
			['to-extension--select-size-large', 			'click-613-623-633-643-1-1-1'],

			['to-extension--track--view', 			        'click-811-821-831-841-1-1-1'],
			['to-extension--track--clip', 			        'click-812-822-832-842-1-1-1'],
			['to-extension--track--theme-popup', 			'click-813-823-833-843-1-1-1'],
			['to-extension--track--settings', 			    'click-814-824-834-844-1-1-1'],

			
			['to-browser--evernote-login-show', 			'click-411-421-431-441-1-1-1'],
			['to-browser--evernote-login-failed', 			'click-412-422-432-442-1-1-1'],
			['to-browser--evernote-login-failed--username', 'click-413-423-433-443-1-1-1'],
			['to-browser--evernote-login-failed--password', 'click-414-424-434-444-1-1-1'],
			['to-browser--evernote-login-successful', 		'click-415-425-435-445-1-1-1'],

			['to-browser--evernote-clip-successful', 		'click-711-721-731-741-1-1-1'],
			['to-browser--evernote-clip-failed', 			'click-712-722-732-742-1-1-1']
		]
	;

	for (var i=0,_i=__custom_events.length,e=false,k=false; i<_i; i++)
	{
		e = __custom_events[i];
		k = e[1].split('-');
		
		__custom_events__names_to_keys[e[0]] = e[1];
		__custom_events__keys_to_names[e[1]] = e[0];
		__custom_events__names_to_objects[e[0]] =
		{
			'_1': k[1],
			'_2': k[2],
			'_3': k[3],
			'_4': k[4],
			'_5': (k[5] == 1 ? true : false),
			'_6': (k[6] == 1 ? true : false),
			'_7': (k[7] == 1 ? true : false)
		};
	}
	
	var __custom_events__get_key = function (_event)
	{
		return 'click'
			+'-'+_event.screenX
			+'-'+_event.screenY
			+'-'+_event.clientX
			+'-'+_event.clientY
			+'-'+(_event.ctrlKey ? 1 : 0)
			+'-'+(_event.altKey ? 1 : 0)
			+'-'+(_event.shiftKey ? 1 : 0)
		;
	};
	
	var __custom_events__dispatch = function (_custom_event_object, _document, _window)
	{
		var _e = _document.createEvent("MouseEvents");
		
		_e.initMouseEvent(
			"click", true, true, _window, 0, 
			_custom_event_object['_1'], _custom_event_object['_2'], _custom_event_object['_3'], _custom_event_object['_4'], 
			_custom_event_object['_5'], _custom_event_object['_6'], _custom_event_object['_7'], 
			false, 0, null
		);
		
		_document.dispatchEvent(_e);
	};
	
		
		//	custom events
		_d.addEventListener('click', function(_event)
		{
			var 
				_event_key = __custom_events__get_key(_event),
				_event_name = __custom_events__keys_to_names[_event_key],
				_stop = false
			;
			
			switch (_event_name)
			{
				/* select theme */
				/* ============ */
					case 'to-extension--select-theme-1': __readable_by_evernote.__save__select_theme('theme-1'); _stop = true; break;
					case 'to-extension--select-theme-2': __readable_by_evernote.__save__select_theme('theme-2'); _stop = true; break;
					case 'to-extension--select-theme-3': __readable_by_evernote.__save__select_theme('theme-3'); _stop = true; break;

					case 'to-extension--select-theme-custom': __readable_by_evernote.__save__select_theme__custom(); _stop = true; break;
					
				/* select size */
				/* =========== */
					case 'to-extension--select-size-small': 	__readable_by_evernote.__save__select_size('small'); 	_stop = true; break;
					case 'to-extension--select-size-medium': 	__readable_by_evernote.__save__select_size('medium'); 	_stop = true; break;
					case 'to-extension--select-size-large': 	__readable_by_evernote.__save__select_size('large'); 	_stop = true; break;
			
					
				/* evernote */
				/* ======== */
					case 'to-extension--evernote-clip':
						
	//	check login
	//		if not logged in, try stored log in 
	//			on successfull login, do clip again
	//			on failed login, or no stored login, show login form
	//	
	//	try clip
	//		on fail, because of login, try stored login
	//			on successfull login, try clip again
	//			on failed login, or no stored login, show login form
	//	============================================================

	
	//	logout on next action
	//	=====================
		if (__readable_by_evernote.__get_stored_evernote_logoutOnNextAction()) { __readable_by_evernote.__evernote_remote.logout(); }
	
	
	//	stored login
	//	============
		var _storedLogin = __readable_by_evernote.__get_stored_evernote_credentials();
	
	
	var 
		_iframe = _d.getElementById('readable_iframe'),
		_doc = (_iframe.contentDocument || _iframe.contentWindow.document),
		
		_bodyElement = _doc.getElementById('text'),
		_tagElement = _d.getElementById('__readable_var__clip_tag'),
		
		__url = _d.defaultView.location.href, 
		__title = _d.title, 
		__body = _bodyElement.innerHTML, 
		__tag = __decodeURIComponentForReadable(_tagElement.innerHTML)
	;

	//	remove fotnoted links
	__body = __body.replace(/<sup class="readableLinkFootnote">[^<]*<\/sup>/gi, '');
	__body = __body.replace(/<ol id="footnotedLinks">[\s\S]*?<\/ol>/gi, '');
	
	
	switch (true)
	{

		//	not connected / logged-in
		//	and we know this -- so do connect/login
		//	=======================================
		case (!(__readable_by_evernote.__evernote_remote.is__connected)):
		case (!(__readable_by_evernote.__evernote_remote.is__loggedIn)):
		
			//	no stored login
			//	===============
			if (_storedLogin == false) { __custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-login-show'], _d, _d.defaultView); return; }
		
			//	do stored login
			//	================
			__readable_by_evernote.__evernote_remote.login
			(
				_storedLogin.username,
				_storedLogin.password,

				//	success | login
				function ()
				{
					__readable_by_evernote.__evernote_remote.clip
					(
						__url,
						__title,
						__body,
						__tag,

						//	success | clip
						function () { __custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-clip-successful'], _d, _d.defaultView); },

						//	failure | clip
						function (_failReason) { __custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-clip-failed'], _d, _d.defaultView); }
					);
				},

				//	failure | login
				function (_failReason) { __custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-login-show'], _d, _d.defaultView); }
			);
		
			break;
			
			
		//	should be both connected and logged in
		//		in case it fails because of login, we try another stored login
		//	===================================================================
		default:

			__readable_by_evernote.__evernote_remote.clip
			(
				__url,
				__title,
				__body,
				__tag,
				
				//	success | clip
				function ()	{ __custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-clip-successful'], _d, _d.defaultView);	},
				
				//	failure | clip
				function (_failReason)
				{
					//	failure because of soemthing else
					if (_failReason == 'login'); else { __custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-clip-failed'], _d, _d.defaultView); return; }

					//	no stored login
					if (_storedLogin == false) { __custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-login-show'], _d, _d.defaultView); return; }
					
					//	try stored login
					__readable_by_evernote.__evernote_remote.login
					(
						_storedLogin.username,
						_storedLogin.password,
						
						//	success | login
						function ()
						{
							__readable_by_evernote.__evernote_remote.clip
							(
								__url,
								__title,
								__body,
								__tag,
								
								//	success | clip
								function () { __custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-clip-successful'], _d, _d.defaultView);	},
								
								//	failure | clip
								function () { __custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-clip-failed'], _d, _d.defaultView); }
							);
						},
						
						//	failure | login
						function () { __custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-login-show'], _d, _d.defaultView); }
					);
				}
			);
		
			break;
	}

						_stop = true;
						break;
					
					case 'to-extension--evernote-login':
						
	//	do login
	//		store login, if rememberMe
	//	==============================

	var 
		_iframe = _d.getElementById('readable_iframe'),
		_doc = (_iframe.contentDocument || _iframe.contentWindow.document),
		
		_userElement = _doc.getElementById('evernote_login__username'),
		_passElement = _doc.getElementById('evernote_login__password'),
		_rememberMeElement = _doc.getElementById('evernote_login__rememberMe'),

		__user = (_userElement.value > '' ? _userElement.value : ''),
		__pass = (_userElement.value > '' ? _passElement.value : ''),
		__rememberMe = (_rememberMeElement.checked == true ? true : false)
	;

	__readable_by_evernote.__evernote_remote.login
	(
		__user,
		__pass,
		
		//	success | login
		function ()
		{
			//	save credentials
			//	================
				if (__rememberMe)
				{
					__readable_by_evernote.__set_stored_evernote_credentials({
						'username': __user,
						'password': __pass
					});
				}
			
			//	raise event	
			__custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-login-successful'], _d, _d.defaultView);
		},
		
		//	fail | login
		function (_failReason)
		{
			switch (_failReason)
			{
				case 'username': 	__custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-login-failed--username'], _d, _d.defaultView); break;
				case 'password': 	__custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-login-failed--password'], _d, _d.defaultView); break;
				default: 			__custom_events__dispatch(__custom_events__names_to_objects['to-browser--evernote-login-failed'], _d, _d.defaultView); break;
			}
		}
	);

						_stop = true;
						break;
					

				/* settings */
				/* ======== */
					case 'to-extension--open-settings-theme':
						window.openDialog('chrome://readable-by-evernote/content/options.xul#showCustom');
						_stop = true;
						break;

					case 'to-extension--open-settings':
						window.openDialog('chrome://readable-by-evernote/content/options.xul');
						_stop = true;
						break;

			}
		
			if (_stop)
			{
				_event.stopPropagation();
				_event.preventDefault();
			}
		
		}, true);
	}

